import React, { useState, useEffect, useCallback } from 'react';
import { Select } from 'antd';
import moment from 'moment';
import debounce from 'lodash/debounce';

import styles from './style.less';
import TMEAvatar from '../TMEAvatar';

const { Option } = Select;

const totalUsersKey = '_arrusers';
const userDataUrl = 'http://top.oa.com/js/users.js';

type Props = {
  value?: string[];
  placeholder: string;
  isMultiple?: boolean;
  onChange?: (owners: string[]) => void;
  [key: string]: any;
};

type RawUserData = [string, string];

interface OptionData {
  value: string;
  text: string;
}

declare global {
  interface Window {
    [totalUsersKey]: RawUserData[];
  }
}

const SelectPerson: React.FC<Props> = ({
  value,
  placeholder,
  isMultiple = true,
  onChange,
  ...restProps
}) => {
  const [data, setData] = useState<OptionData[]>([]);

  const initList = useCallback(() => {
    const initData = Array.isArray(window[totalUsersKey]) ? window[totalUsersKey].slice(0, 50) : [];
    setData(initData.map((item) => ({ value: item[0], text: item[1] })));
  }, [setData]);

  useEffect(() => {
    if (typeof window[totalUsersKey] === 'undefined') {
      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `${userDataUrl}?_=${moment().format('YYYYMMDD')}`;
      script.onload = () => {
        initList();
      };
      document.body.appendChild(script);
    }
  }, []);

  const handleSearch = useCallback(
    debounce((val: string) => {
      if (val) {
        const options = window[totalUsersKey]
          .filter((item) => item[1].includes(val))
          .sort((a, b) => a[1].indexOf(val) - b[1].indexOf(val))
          .map((item) => {
            return {
              value: item[0],
              text: item[1],
            };
          });
        setData(options);
      } else {
        initList();
      }
    }, 300),
    [setData],
  );

  const handleChange = (owners: string[]) => {
    if (onChange) {
      onChange(owners);
    }
  };

  const options = data.map((d) => {
    return (
      <Option key={d.value} value={d.value}>
        <TMEAvatar size="small" staffName={d.value} />
        <span className={styles.userText}>{d.text}</span>
      </Option>
    );
  });

  return (
    <Select
      showSearch
      mode={isMultiple ? 'multiple' : undefined}
      value={value}
      placeholder={placeholder}
      style={{ width: '100%' }}
      allowClear
      defaultActiveFirstOption={false}
      showArrow={false}
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={null}
      {...restProps}
    >
      {options}
    </Select>
  );
};

export default SelectPerson;
